/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pku.lbs.web;

import cn.edu.pku.ss.lbs.service.LBSService;
import java.io.File;
import java.io.IOException;

import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import pku.lbs.core.Constants;
import pku.lbs.interfaces.DummyClass;

/**
 *
 * @author yongchao
 */
public class UploadWeb {

    private static UploadWeb instance = null;

    private UploadWeb() { }

    static public UploadWeb getInstance() {
        if (instance == null) {
            instance = new UploadWeb();
        }
        return instance;
    }

    private JSONObject uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //GET UPLOAD FILE AND SAVE TO photoTempPath
        String fileTempPath = null;
        JSONObject json = new JSONObject();
        String userName = null;
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            try {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List<FileItem> items = upload.parseRequest(request);
                Iterator<FileItem> iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    //processFormField
                    if (item.isFormField()) {
                        if (item.getFieldName().equals("user")) {
                            userName = item.getString("UTF-8");
                        }
                    } else {
                        String fileName = item.getName();
                        if (fileName != null && !fileName.trim().equals("")) {
                            Long size = item.getSize();
                            Double MAX_SIZE = Constants.UPLOAD_MAXSIZE * 1024 * 1024;
                            if( size > MAX_SIZE){
                                throw new Exception("文件太大");
                            }
                            String tempDirectory = Constants.UPLOAD_DIR + "temp/";
                            File uploadedFile = new File(tempDirectory);
                            if (!uploadedFile.exists()) {
                                uploadedFile.mkdirs();
                            }
                            int index = fileName.lastIndexOf(".");
                            String ext = fileName.substring(index);
                            String filename = fileName + "_" + System.currentTimeMillis();
                            if (userName != null) {
                                filename = userName + '@' + filename;
                            }
                            File savedFile = new File(uploadedFile, filename + ext);
                            try {
                                item.write(savedFile);
                            } catch (Exception ex) {
                                Logger.getLogger(UploadWeb.class.getName()).log(Level.SEVERE, null, ex);
                            }
                            //success upload
                            fileTempPath = tempDirectory + filename + ext;

                            json.put("RETURN", true);
                            json.put("saved_path", fileTempPath);
                        }
                    }
                }
            } catch (Exception ex) {
                json.put("RETURN", false);
                json.put("MESSAGE", "出错啦");
            }
        }
        return json;
    }

    public String doSendMsg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String message = request.getParameter("message");
        String posX = request.getParameter("pos_x");
        String posY = request.getParameter("pos_y");

        System.out.println("message:" + message + " posX: " + posX + " posY: " + posY);
        LBSService lbsService = LBSService.getInstance();
        String zoneId = lbsService.getZone(Integer.valueOf(posX), Integer.valueOf(posY));
        System.out.println("zoneId: " + zoneId);
        lbsService.sendMessage(zoneId, message);

        JSONObject json = new JSONObject();
        json.put("RETURN", true);

        return json.toString();
    }

    public String doSendSingleMsg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String message = request.getParameter("message");
        String terminal = request.getParameter("user");
//        String posX = request.getParameter("pos_x");
//        String posY = request.getParameter("pos_y");

        LBSService lbsService = LBSService.getInstance();
        String zone = lbsService.getZoneByTerminal(terminal);
        lbsService.sendMessage(zone, terminal, message);

        JSONObject json = new JSONObject();
        json.put("RETURN", true);

        return json.toString();
    }

    public String doSendFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String posX = request.getParameter("pox_x");
        String posY = request.getParameter("pos_y");

        JSONObject json = uploadFile(request, response);
        if ( json.getBoolean("RETURN") ) {
            // TODO
//            DummyClass dummy = new DummyClass();
//            String zoneId = dummy.getZoneByPos(posX, posY);
//            String nodeId = dummy.getNodeByZone( zoneId );
//            dummy.sendFile(nodeId, (String) json.get("saved_path"));
        } else {
            
        }

        return json.toString();
    }

    public String doSendSingleFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String user = request.getParameter("user");

        JSONObject json = uploadFile(request, response);
        if ( json.getBoolean("RETURN") ) {
            // TODO
            DummyClass dummy = new DummyClass();
            dummy.sendFile(user, (String) json.get("saved_path"));
        } else {

        }

        return json.toString();
    }

    public String doUploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        return uploadFile(request, response).toString();
    }
}
